<?php
function p($data,$die = false)
{
	$str = '<pre style="display: block;padding: 9.5px;margin: 44px 0 0 0;font-size: 20px;line-height: 1.42857;color: red;word-break: break-all;word-wrap: break-word;background-color: #F5F5F5;border: 1px solid #CCC;border-radius: 4px;">';
	// 如果是boolean或者null直接显示文字；否则print
	if (is_bool($data)) 
	{
		$show_data            = $data ? 'true': 'false';
	}elseif (is_null($data)) 
	{
		$show_data            = 'null';
	}
	elseif ($data == '') 
	{
		$show_data            = "''";
	}
	else
	{
		$show_data  = print_r($data,true);
	}
		$str          .= $show_data;
		$str          .= '</pre>';
	echo $str;
	if(true == $die)
	{
		die();
	}

}

//获取随机码
function getRandCode($status=0,$max=0)
{
	switch ($status)
	{
		case 0:
			$array = array(
					'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
			);
			break;
		case 1:
			$array = array(
					'0','1','2','3','4','5','6','7','8','9'
			);
			break;
		default:
			$array = array(
					'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
			);
	}
	$tmpstr = '';
	for ($i=0; $i < $max; $i++) {
		$key = rand(0,$max-1);
		$tmpstr .=$array[$key];
	}
	return $tmpstr;
}

/**
 * @param string $url get请求地址
 * @param int $httpCode 返回状态码
 * @return mixed
 */
function curl_get($url, &$httpCode = 0)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	//不做证书校验,部署在linux环境下请改为true
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
	$file_contents = curl_exec($ch);
	$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);
	return $file_contents;
}

function curl_post($url, array $params = array())
{
	$data_string = json_encode($params);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
	curl_setopt(
			$ch, CURLOPT_HTTPHEADER,
			array(
					'Content-Type: application/json'
			)
	);
	$data = curl_exec($ch);
	curl_close($ch);
	return ($data);
}
function curl_form($sumbit_url,$post_data){
	//初始化
	$ch = curl_init();
	//设置变量
	curl_setopt($ch, CURLOPT_URL, $sumbit_url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//执行结果是否被返回，0是返回，1是不返回
	curl_setopt($ch, CURLOPT_HEADER, 0);//参数设置，是否显示头部信息，1为显示，0为不显示
	//表单数据，是正规的表单设置值为非0
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, 1);//设置curl执行超时时间最大是多少
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	//执行并获取结果
	$output = curl_exec($ch);
	if($output === FALSE)
	{
		echo "<br/>","cUrl Error:".curl_error($ch);
	}
	//    释放cURL句柄
	curl_close($ch);
	return $output;
	
}
function charsetToUTF8($mixed)
{
    if (is_array($mixed)) {
        foreach ($mixed as $k => $v) {
            if (is_array($v)) {
                $mixed[$k] = charsetToUTF8($v);
            } else {
                $encode = mb_detect_encoding($v, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5','EUC-CN'));
                if ($encode == 'EUC-CN') {
                    $mixed[$k] = iconv('GBK', 'UTF-8', $v);
                }
            }
        }
    } else {
        $encode = mb_detect_encoding($mixed, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5','EUC-CN'));
        if ($encode == 'EUC-CN') {
            $mixed = iconv('GBK', 'UTF-8', $mixed);
        }
    }
    return $mixed;
}

function substr_replace_cn($string, $repalce = '*',$start = 0,$len = 0) {
	$count = mb_strlen($string, 'UTF-8'); //此处传入编码，建议使用utf-8。此处编码要与下面mb_substr()所使用的一致
	if(!$count) { return $string; }
	if($len == 0){
		$end = $count; 	//传入0则替换到最后
	}else{
		$end = $start + $len;		//传入指定长度则为开始长度+指定长度
	}
	$i = 0;
	$returnString = '';
	while ($i < $count) {		//循环该字符串
		$tmpString = mb_substr($string, $i, 1, 'UTF-8'); // 与mb_strlen编码一致
		if ($start <= $i && $i < $end) {
			$returnString .= $repalce;
		} else {
			$returnString .= $tmpString;
		}
		$i ++;
	}
	return $returnString;
}

function show($status=1,$msg='',$url='',$data='') {
	header('Content-Type:application/json; charset=utf-8');
	$result = array(
			'status' 	=>	$status,
			'msg'	=>	$msg,
			'url'       =>  $url,
			'data'		=>	$data ,
	);
	exit(json_encode($result));
}

// 获取两个日期之间的天数
function getDaysBetweenDate($day1, $day2){
	$second1 = strtotime($day1);
	$second2 = strtotime($day2);
	if ($second1 < $second2) {
		$tmp = $second2;
		$second2 = $second1;
		$second1 = $tmp;
	}
	return  ($second1 - $second2);
}

//获取日期和今天的秒数
function getDaysBetweenToday($nowtime,$repayDate,$oneSeconds){
	$arr=array();
	for($time=$nowtime;$time<$repayDate;$time=$time+$oneSeconds){
		$arr[]=date("Y-m-d H:i:s",$time);
	}
	return $arr;
}

//获取订单号
function getOrderNo()
{
	$time = substr(date('YmdHis'),2,12);
	$str = getRandCode(1,4);
	return $time.$str;
}

//日志写入
function LogWrite($logs = '', $label =  '')
{
	$file_name = APP_PATH . date('Y-m-d') . '.txt';
	$now_time = date('Y-m-d H:i:s');
	$log_message = "[$now_time]:" . $label . var_export($logs, true) . PHP_EOL;
	file_put_contents($file_name, $log_message, FILE_APPEND);
}

/**
 * 验证身份证号
 * @param $vStr
 * @return bool
 */
function isCreditNo($vStr)
{
	$vCity = array(
		'11','12','13','14','15','21','22',
		'23','31','32','33','34','35','36',
		'37','41','42','43','44','45','46',
		'50','51','52','53','54','61','62',
		'63','64','65','71','81','82','91'
	);

	if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;

	if (!in_array(substr($vStr, 0, 2), $vCity)) return false;

	$vStr = preg_replace('/[xX]$/i', 'a', $vStr);
	$vLength = strlen($vStr);

	if ($vLength == 18)
	{
		$vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
	} else {
		$vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
	}

	if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
	if ($vLength == 18)
	{
		$vSum = 0;

		for ($i = 17 ; $i >= 0 ; $i--)
		{
			$vSubStr = substr($vStr, 17 - $i, 1);
			$vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
		}

		if($vSum % 11 != 1) return false;
	}

	return true;
}

/**
 * 生成随机数
 * @param $length 需要生成随机数的长度
*/
function randomkeys($length)
{
	$pattern = '1234567890abcdefghijklmnopqrstuvwxyz   
               ABCDEFGHIJKLOMNOPQRSTUVWXYZ';
	$key = null;
	for ($i = 0; $i < $length; $i++) {
		$key .= $pattern{mt_rand(0, 35)};    //生成php随机数
	}
	return $key;
}

//把时间转成：2017-01-01 的格式
function changeTimeStamp($date) {
	return substr($date,0,10);
}

//把一段很长的字符串变成数组
function cExplode($str) {
    if(strlen($str)>20) {
        $index = 1;
        $ret = '';
        for($i = 0; $i < strlen($str); $i++) {
            if(($index)%30 === 0) {
                $ret.= '<br>';
            }else {
                $ret .= $str[$i];
            }
            if($str[$i] == ',') {
                $index++;
            }
        }
        return $ret;
    }else {
        return $str;
    }
}
//红包生成算法 type=0平分 type=1不平分
function randBonus($total=0, $num=3, $type=0,$min=0.01){
	$arr = [];

	if( $type == 0 ){
		$money = $total/$num;
		for ($i=1;$i<$num;$i++){
			$arr[$i]['money'] = $money;
			$total=$total-$money;
			$arr[$i]['lastmoney'] = $total;//剩余金额
		}

	}elseif($type == 1){
		for ($i=1;$i<$num;$i++){
			$safe_total=($total-($num-$i)*$min)/($num-$i);//随机安全上限
			$money=mt_rand($min*100,$safe_total*100)/100;
			$total=$total-$money;
			$arr[$i]['money'] = $money;
			$arr[$i]['lastmoney'] = $total;//剩余金额
		}

	}
	$lastArr = ['money' => $total,'lastmoney'=>0];
	array_push($arr,$lastArr);
	return $arr;
}
function importExcel($file='',$sheet=0)
{
	$file = iconv("utf-8","gb2312",$file);
	if(empty($file) || !file_exists($file)){
			throw new UploadImgException([
			'msg' =>'文件不存在'
		]);
	}
	$objRead = new \PHPExcel_Reader_Excel2007();
	if(!$objRead->canRead($file)){
		$objRead = new \PHPExcel_Reader_Excel5();
		if(!$objRead->canRead($file)){
				throw new UploadImgException([
				'msg' =>'文件不存在'
		]);
		}
	}
	$cellName = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
	$obj = $objRead->load($file);
	$currSheet = $obj->getSheet($sheet);
	$columnH = $currSheet->getHighestColumn();
	$columnCnt = array_search($columnH,$cellName);
	$rowCnt = $currSheet->getHighestRow();
	$data = [];
	for($_row=1;$_row<=$rowCnt;$_row++){
		for($_column=0;$_column<=$columnCnt;$_column++){
			$cellId =$cellName[$_column].$_row;
			$cellValue = $currSheet->getCell($cellId)->getValue();
			if($cellValue instanceof \PHPExcel_RichText){
				$cellValue = $cellValue->__toString();
			}
			$data[$_row][$cellName[$_column]] = $cellValue;
		}
	}
	return $data;
}
//数组转树形图
function arrToTree(array $data=[],$parentId=null,$level=1)
{
	$result = array();
	foreach($data as $v)
	{
		if($v['blChnlId'] == $parentId)
		{
			$v['level'] = $level;
			$v['children'] = arrToTree($data,$v['chnlId'],$level+1); 
			if($v['children'] == null)
			{  
				unset($v['children']);            
			}
			$result[] = $v;     
		}
	}
     return $result;
}
//获取下级代理信息
function getNextAgent($agent_id='',$level=1)
{
	$agentlist = [];
	$list = getAgentList();
	if($list && is_array($list) )
	{
		$tree = arrToTree($list);
		
	}
	$res = getAgentArray($tree,$agent_id,$level);
	// foreach($res['children'] as $k=>$v)
	// {
	// 	if($v['level']>1){
	// 		$res['children'][$k+1] = $v['children'][0];
	// 		unset($res['children'][$k]['children']);
	// 	}
	// 	return $res;
	// }
	return $res;

}
function getAgentArray($data = [],$agent_id = '',$level = 1,$lastArr = [])
{
	foreach($data as $v){
		if($level == 1 && $v['chnlId'] == $agent_id){
			$agentlist = $v;
			return $agentlist;
		}elseif($level > 1 && array_key_exists('children',$v)){
			$agentlist = getAgentArray($v['children'],$agent_id,$level-1);
			return $agentlist;
		}
	} 
	
}

//查询代理商费率
function getFee($agentId='')
{
	$arr['reqType'] = 'chnlFeeDetail';
	$arr['agentId'] =  config('api.agentId');
	$arr['chnlId'] = $agentId;
	$arr['reqDate'] = date('Ymd');
	$arr['reqTime'] = date('His');
	$url = config('api.reqUrl').'merEntry.do';
	$passStr = config('api.passStr');
	$str = $arr['reqType'].$arr['agentId'].$arr['chnlId'].$arr['reqDate'].$arr['reqTime'].$passStr ;
	$arr['chkValue'] = md5($str);
	$resdata = curl_form($url,$arr);
	$list = json_decode(mb_convert_encoding($resdata,'UTF-8','GBK'),true)['feeInfo'];
	return $list;
}
//查询代理商详情
function getAgentDetail($chnlId='')
{
	$arr['reqType'] = 'chnlBaseDetail';
	$arr['agentId'] =  config('api.agentId');
	$arr['chnlId'] = $chnlId;
	$arr['reqDate'] = date('Ymd');
	$arr['reqTime'] = date('His');
	$url = config('api.reqUrl').'merEntry.do';
	$passStr = config('api.passStr');
	$str = $arr['reqType'].$arr['agentId'].$arr['chnlId'].$arr['reqDate'].$arr['reqTime'].$passStr ;
	$arr['chkValue'] = md5($str);
	$resdata = curl_form($url,$arr);
    $list = json_decode(mb_convert_encoding($resdata,'UTF-8','GBK'),true);
	return $list;
}
//查询代理商列表
function getAgentList($chnlId='',$chnlName='')
{
	$arr = array();
	$arr['reqType'] = 'chnlList';
	$arr['agentId'] =  config('api.agentId');
	$arr['chnlId'] = '';
	$arr['chnlName'] = '';
	$arr['blChnlId'] = '';
	$arr['pageNum'] = '1';
	$arr['pageSize'] = '100';
	$url = config('api.reqUrl').'merEntry.do';
	$passStr = config('api.passStr');
	$str = $arr['reqType'].$arr['agentId'].$arr['pageNum'].$arr['pageSize'].$passStr ;
	$arr['chkValue'] = md5($str);
	$resdata = curl_form($url,$arr);
	$list = json_decode(mb_convert_encoding($resdata,'UTF-8','GBK'),true)['chnlsInfo'];
	return $list;
}
function getAgentListById($chnlId='')
{
	$arr = array();
	$arr['reqType'] = 'chnlList';
	$arr['agentId'] =  config('api.agentId');
	$arr['chnlId'] = $chnlId;
	$arr['chnlName'] = '';
	$arr['blChnlId'] = '';
	$arr['pageNum'] = '1';
	$arr['pageSize'] = '100';
	$url = config('api.reqUrl').'merEntry.do';
	$passStr = config('api.passStr');
	$str = $arr['reqType'].$arr['agentId'].$arr['chnlId'].$arr['pageNum'].$arr['pageSize'].$passStr ;
	
	$arr['chkValue'] = md5($str);
	$resdata = curl_form($url,$arr);
	$list = json_decode(mb_convert_encoding($resdata,'UTF-8','GBK'),true);
	return $list;
}
